package com.atguigu.flinkState;

import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * @author wky
 * @create 2021-07-19-9:35
 */
// ListState 针对每个传感器输出最高的3个水位值
public class State_Keyed_ListState {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();

        senv.setParallelism(1);
        DataStreamSource<String> source = senv.socketTextStream("hadoop102", 9999);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });
        KeyedStream<WaterSensor, String> keyedStream = map.keyBy(WaterSensor::getId);
        //针对每个传感器输出最高的3个水位值
        keyedStream.process(new KeyedProcessFunction<String, WaterSensor, String>() {
            //设置状态值
            private ListState<Integer> listState;

            @Override
            public void open(Configuration parameters) throws Exception {
                //初始化 防止空指针异常 加载时间的问题
                listState=getRuntimeContext().getListState(new ListStateDescriptor<Integer>("list",Integer.class));
            }

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                listState.add(value.getVc());
                Iterable<Integer> integers = listState.get();//迭代器只能使用一次
                ArrayList<Integer> list = new ArrayList<>();
                for (Integer integer : integers) {
                    list.add(integer);
                }
                list.sort((a1,a2)->(a2-a1));
                if (list.size()>3){
                    list.remove(3);
                }
                listState.clear();
                listState.addAll(list);
               // listState.update(list);
                out.collect(list.toString());

            }
        }).print();
        senv.execute();


    }
}
